Use data provided in the library

reference https://www.r-graph-gallery.com/175-choropleth-map-cartography-pkg.html.

# Use the cartography library to do the choropleth map
library(cartography)

# Load data
data(nuts2006)

# Build a choropleth
choroLayer(spdf = nuts2.spdf, df = nuts2.df, var = "pop2008" , legend.pos = "right")

# title("Population in 2008")

Use data provided in a shape file

reference https://www.r-graph-gallery.com/175-choropleth-map-cartography-pkg.html

…

# Download the shape file from the web and unzip it:
download.file("http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip" , destfile="world_shape_file.zip")
# system("unzip world_shape_file.zip")

# Load it as a geospatial object in R
library(rgdal)
## Loading required package: sp
## rgdal: version: 1.5-12, (SVN revision 1018)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 3.0.4, released 2020/01/28
## Path to GDAL shared files: C:/Users/kamayudi/Documents/R/win-library/4.0/rgdal/gdal
## GDAL binary built with GEOS: TRUE 
## Loaded PROJ runtime: Rel. 6.3.1, February 10th, 2020, [PJ_VERSION: 631]
## Path to PROJ shared files: C:/Users/kamayudi/Documents/R/win-library/4.0/rgdal/proj
## Linking to sp version:1.4-2
## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
## use options("rgdal_show_exportToProj4_warnings"="none") before loading rgdal.
my_spdf <- readOGR( dsn= "world_shape_file" , layer="TM_WORLD_BORDERS_SIMPL-0.3", verbose=FALSE) 
africa <- my_spdf[my_spdf@data$REGION==2 , ]

africa@data$POP2005 <- as.numeric(africa@data$POP2005)

# Use the cartography library to do the choropleth map
library(cartography)
choroLayer(spdf = africa, df = africa@data, var = "POP2005")

# title("Number of people living in Africa in 2005")

Use data in geoJSON format : USA

library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(rjson)

url <- 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
counties <- rjson::fromJSON(file=url)
url2<- "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
df <- read.csv(url2, colClasses=c(fips="character"))
g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showlakes = TRUE,
  lakecolor = toRGB('white')
)
fig <- plot_ly()
fig <- fig %>% add_trace(
    type="choropleth",
    geojson=counties,
    locations=df$fips,
    z=df$unemp,
    colorscale="Viridis",
    zmin=0,
    zmax=12,
    marker=list(line=list(
      width=0)
    )
  )
fig <- fig %>% colorbar(title = "Unemployment Rate (%)")
## Warning: `arrange_()` is deprecated as of dplyr 0.7.0.
## Please use `arrange()` instead.
## See vignette('programming') for more help
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_warnings()` to see where this warning was generated.
fig <- fig %>% layout(
    title = "2016 US Unemployment by County"
)

fig <- fig %>% layout(
    geo = g
  )

fig

Use data in geoJSON format : Victoria

reference: https://towardsdatascience.com/r-and-leaflet-to-create-interactive-choropleth-maps-8515ef83e275

library(rgeos)
## rgeos version: 0.5-3, (SVN revision 634)
##  GEOS runtime version: 3.8.0-CAPI-1.13.1 
##  Linking to sp version: 1.4-2 
##  Polygon checking: TRUE
library(maptools)
## Checking rgeos availability: TRUE
library(leaflet)

setwd("C:/Users/kamayudi/Documents/GitHub/Map-Visualisation/")
vicmapdata <- readShapeSpatial("vic-july-2018-esri/E_AUGFN3_region.shp")
## Warning: readShapeSpatial is deprecated; use rgdal::readOGR or sf::st_read
## Warning: readShapePoly is deprecated; use rgdal::readOGR or sf::st_read
plot(vicmapdata)

electiondata <- read.csv("vic_elect_results.csv")
summary(electiondata)
##    Division            State           Successful.Party    TCP.Margin       
##  Length:38          Length:38          Length:38          Length:38         
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character
colnames(electiondata) <- c("Divisions", "State", "Party", "Marginal Votes")
summary(electiondata)
##   Divisions            State              Party           Marginal Votes    
##  Length:38          Length:38          Length:38          Length:38         
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character
summary(vicmapdata)
## Object of class SpatialPolygonsDataFrame
## Coordinates:
##         min       max
## x 140.96168 149.97668
## y -39.15919 -33.98043
## Is projected: NA 
## proj4string : [NA]
## Data attributes:
##    E_div_numb       Elect_div     Numccds          Actual      
##  Min.   : 1.00   Aston   : 1   Min.   :267.0   Min.   :100151  
##  1st Qu.:10.25   Ballarat: 1   1st Qu.:337.5   1st Qu.:105494  
##  Median :19.50   Bendigo : 1   Median :354.0   Median :107416  
##  Mean   :19.50   Bruce   : 1   Mean   :359.1   Mean   :106954  
##  3rd Qu.:28.75   Calwell : 1   3rd Qu.:387.0   3rd Qu.:109115  
##  Max.   :38.00   Casey   : 1   Max.   :467.0   Max.   :112265  
##                  (Other) :32                                   
##    Projected        Total_Popu   Australian   Area_SqKm            Sortname 
##  Min.   :107381   Min.   :0    Min.   :0    Min.   :   40.46   Aston   : 1  
##  1st Qu.:109070   1st Qu.:0    1st Qu.:0    1st Qu.:   80.59   Ballarat: 1  
##  Median :109986   Median :0    Median :0    Median :  170.28   Bendigo : 1  
##  Mean   :110372   Mean   :0    Mean   :0    Mean   : 5987.93   Bruce   : 1  
##  3rd Qu.:111484   3rd Qu.:0    3rd Qu.:0    3rd Qu.: 2619.61   Calwell : 1  
##  Max.   :113924   Max.   :0    Max.   :0    Max.   :81962.21   Casey   : 1  
##                                                                (Other) :32
vicmapdata$Elect_div
##  [1] Aston       Ballarat    Bendigo     Bruce       Calwell     Casey      
##  [7] Chisholm    Cooper      Corangamite Corio       Deakin      Dunkley    
## [13] Flinders    Fraser      Gellibrand  Gippsland   Goldstein   Gorton     
## [19] Higgins     Holt        Hotham      Indi        Isaacs      Jagajaga   
## [25] Kooyong     La Trobe    Lalor       Macnamara   Mallee      Maribyrnong
## [31] Mcewen      Melbourne   Menzies     Monash      Nicholls    Scullin    
## [37] Wannon      Wills      
## 38 Levels: Aston Ballarat Bendigo Bruce Calwell Casey Chisholm ... Wills
electiondata$Divisions
##  [1] "Aston"       "Ballarat"    "Bendigo"     "Bruce"       "Calwell"    
##  [6] "Casey"       "Chisholm"    "Cooper"      "Corangamite" "Corio"      
## [11] "Deakin"      "Dunkley"     "Flinders"    "Fraser"      "Gellibrand" 
## [16] "Gippsland"   "Goldstein"   "Gorton"      "Higgins"     "Holt"       
## [21] "Hotham"      "Indi"        "Isaacs"      "Jagajaga"    "Kooyong"    
## [26] "La Trobe"    "Lalor"       "Macnamara"   "Mallee"      "Maribyrnong"
## [31] "McEwen"      "Melbourne"   "Menzies"     "Monash"      "Nicholls"   
## [36] "Scullin"     "Wannon"      "Wills"
setdiff(electiondata$Division, vicmapdata$Elect_div)
## [1] "McEwen"
which(electiondata$Division=="McEwen")
## [1] 31
vicmapdata$Elect_div[31]
## [1] Mcewen
## 38 Levels: Aston Ballarat Bendigo Bruce Calwell Casey Chisholm ... Wills
vicmapdata$Elect_div <- electiondata$Divisions
setdiff(electiondata$Division, vicmapdata$Elect_div)
## character(0)
leaflet(vicmapdata) %>%
  addPolygons(
    stroke = TRUE, 
    color = 'White', 
    weight = 1.5, 
    )
mylabels <- paste(
  "Electorate: ", vicmapdata$Elect_div, "<br/>",
  "Party: ", electiondata$Party, "<br/>",
  "Margin(votes): ", electiondata$`Marginal Votes`
) %>%
  lapply(htmltools::HTML)

leaflet(vicmapdata) %>%
  addPolygons(
    stroke = TRUE, 
    color = 'White', 
    weight = 1.5, 
    label = mylabels,
    labelOptions = labelOptions( 
      style = list("font-weight" = "normal", padding = "3px 8px"), 
      textsize = "13px", 
      direction = "auto"
    )
    )
factpal <- colorFactor(topo.colors(5), unique(electiondata$Party))
leaflet(vicmapdata) %>%
  addPolygons(
    fillColor = ~factpal(electiondata$Party), 
    stroke = TRUE, 
    color = 'White', 
    weight = 1.5, 
    label = mylabels,
    labelOptions = labelOptions( 
      style = list("font-weight" = "normal", padding = "3px 8px"), 
      textsize = "13px", 
      direction = "auto"
    )
    )
htmltitle <- "<h5> How Victoria voted in the 2019 Federal Election | House of Representatives</h5>"

references <- "<h5>References</h5><a target='_blank' href='https://results.aec.gov.au/24310/Website/HouseDivisionalResults-24310.htm'><h5>Election Data</h5></a><a target='_blank' href='https://aec.gov.au/Electorates/gis/gis_datadownload.htm'><h5>Geometric Data</h5></a>"

leaflet(vicmapdata) %>%
  addPolygons(
    fillColor = ~factpal(electiondata$Party), 
    stroke = TRUE, 
    color = 'White', 
    weight = 1.5, 
    label = mylabels,
    labelOptions = labelOptions( 
      style = list("font-weight" = "normal", padding = "3px 8px"), 
      textsize = "13px", 
      direction = "auto"
    )
    ) %>%
  addLegend( pal=factpal, 
             values=~electiondata$Party, 
             opacity=0.3, 
             title = "Political Party", 
             position = "bottomleft" 
             ) %>%
  addControl(html=htmltitle, position = "topright") %>%
  addControl(html=references, position = "bottomright")